package com.zline.foodraise.ui.activity;

import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baidu.mobstat.StatService;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.CustomerFragmentAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.UserBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.ui.fragment.AttentionFragment;
import com.zline.foodraise.ui.fragment.AttentionFragment_;
import com.zline.foodraise.ui.fragment.ProductFragment;
import com.zline.foodraise.ui.fragment.ProductFragment_;
import com.zline.foodraise.util.ImageUtil;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.CircleImageView;
import com.zline.foodraise.view.WrapContentViewPager;
import com.zline.foodraise.wx.WxShareUtil;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by heshantao on 15/7/30.
 * 个人主页
 */
@EActivity(R.layout.activity_personal_home_page)
public class PersonalHomePageActivity extends ZlineActivity {
    private static final String LOG_TAG = PersonalHomePageActivity.class.getSimpleName();
    //用户背景图
    @ViewById(R.id.me_top_person_homepage_bg_iv)
    ImageView person_background_iv;
    //用户头像
    @ViewById(R.id.me_person_icon_civ)
    CircleImageView me_person_icon_civ;
    @ViewById(R.id.me_person_icon_vip)
    ImageView me_person_icon_vip;
    //用户粉丝数
    @ViewById(R.id.me_top_fans_tv)
    TextView fans_num_tv;
    @StringRes(R.string.fans)
    String fans;
    //用户关注数
    @ViewById(R.id.me_top_attention_tv)
    TextView attention_num_tv;
    @StringRes(R.string.attention)
    String attentions;
    //昵称
    @ViewById(R.id.me_person_nickname_tv)
    TextView nickname_tv;
    //签名
    @ViewById(R.id.me_person_signature_value_tv)
    TextView signature_tv;
    @ViewById(R.id.me_person_signature_rl)
    RelativeLayout personal_sigature_rl;
    //+关注
    @ViewById(R.id.me_person_attention_tv)
    TextView attention_tv;
    @StringRes(R.string.add_attention)
    String add_attention;
    @StringRes(R.string.unAttention)
    String cancel_attention;
    //个人认证
    @ViewById(R.id.personal_identify_rl)
    RelativeLayout personal_identify_rl;
    @ViewById(R.id.personal_identify_content_tv)
    TextView identify_tv;
    String identifyStr;
    //个人说明
    @ViewById(R.id.me_person_declare_rl)
    RelativeLayout personal_declare_rl;
    @ViewById(R.id.me_person_declare_value_tv)
    TextView declare_tv;
    String declare;
    Context cxt;
    @ViewById(R.id.me_persion_product_attention_join_tl)
    TabLayout tabLayout;
    @ViewById(R.id.me_persion_product_attention_vg)
    WrapContentViewPager viewPager;
    @Extra
    long userId;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Bean
    HttpDataParsing httpDataParsing;
    @Bean
    ImageUtil imageUtil;
    //用户粉丝数量
    int fansCount;
    //用户关注数
    int attentionCount;
    //用户头像地址
    String person_ico_url;
    //用户背景图片地址
    String person_bg_url;
    //用户昵称
    String nickname;
    //用户个性签名
    String signature;
    //是否关注
    int isAttention = 0;
    //是否通过点击关注、取消关注
    boolean doAttentionOrCancel = false;
    @Pref
    AppPref_ appPref;
    //1代表开店，0,代表没开店
    int isOpenShop;
    //身份认证类型：0-未认证，1-认证大V，2-活跃用户
    int authenticateType;
    @Bean
    NetworkUtil networkUtil;
    CustomerFragmentAdapter fragmentAdapter;
    FragmentManager fManager;
    ProductFragment productFragment;
    AttentionFragment attentionFragment;
    ArrayList<Fragment> fragments;
    @Bean
    WxShareUtil wxUtil;
    String shareResult;
    MaterialDialog shareDialog;

    @AfterInject
    void doSomeAfterInject() {
        cxt = PersonalHomePageActivity.this;
    }

    @AfterViews
    void doSomeAfterView() {
        requestData();
        initView();
    }

    void initView() {
        initViewPage();
        if (userId == appPref.userId().get()) {
            attention_tv.setVisibility(View.GONE);
        }
    }

    //请求网络数据
    void requestData() {
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            requestUserInfo();
            if (appPref.userId().get() > 0) {
                requestAttention2User();
            } else {
                setAttention(0);
            }
        } else {
            TUtil.showShort(PersonalHomePageActivity.this, R.string.no_network);
        }
    }


    //获取操作者对该用户的关注
    void requestAttention2User() {
        httpOperator.requestAttention2Other(httpUtil, userId, requestAttention2UserHandler);
    }

    //获取操作者对该用户的关注回调
    AsyncHttpResponseHandler requestAttention2UserHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestAttention2UserHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        boolean attention = response.getBoolean(Constant.IS_ATTENTION);
                        isAttention = attention == true ? 1 : 0;
                        setAttention(isAttention);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    dissLoadingDialog();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dissLoadingDialog();
        }
    };


    //请求用户基本信息
    void requestUserInfo() {
        httpOperator.requestUserInfo(httpUtil, userId, requestUserInfoHandler);
    }

    //获取用户基本信息回调
    AsyncHttpResponseHandler requestUserInfoHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestUserInfoHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        UserBean userBean = httpDataParsing.getUserBean(response);
                        setUserInfo(userBean);
                        setViewPager(userBean);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    dissLoadingDialog();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dissLoadingDialog();
        }
    };


    //代表关注状态改变回调
    AsyncHttpResponseHandler changeAttentionStatusHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs____changeAttentionStatusHandler______" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        isAttention = isAttention == 0 ? 1 : 0;
                        changeAttentaionStatus(isAttention);
                    } else {
                        httpErro.showAttentionErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };

    //设置用户基本信息
    void setUserInfo(UserBean userBean) {
        if (userBean != null) {
            ImageLoader imageLoader = ImageLoader.getInstance();
            DisplayImageOptions person_icon_options = imageUtil.
                    getDisplayImageOptions(R.mipmap.default_person_icon,
                            R.mipmap.default_person_icon, R.mipmap.default_person_icon);
            DisplayImageOptions person_bg_options = imageUtil.
                    getDisplayImageOptions(R.mipmap.person_bg,
                            R.mipmap.person_bg, R.mipmap.person_bg);
            fansCount = userBean.getUserFansCount();
            fans_num_tv.setText(fansCount + fans);
            attentionCount = userBean.getUserAttentionCount();
            attention_num_tv.setText(attentionCount + attentions);
            person_ico_url = userBean.getAvatarPicUrl();
            authenticateType = userBean.getIdentificateType();
            imageLoader.displayImage(person_ico_url, me_person_icon_civ, person_icon_options);
            if (authenticateType == 1) {//大V
                me_person_icon_vip.setVisibility(View.VISIBLE);

            }
            person_bg_url = userBean.getBackPicUrl();
            imageLoader.displayImage(person_bg_url, person_background_iv, person_bg_options);
            nickname = userBean.getNickName();
            nickname_tv.setText(nickname);
            signature = userBean.getSignature();
            if (StringUtils.isBlank(signature)) {
                personal_sigature_rl.setVisibility(View.GONE);
            } else {
                personal_sigature_rl.setVisibility(View.VISIBLE);
                signature_tv.setText(signature);
            }

            //设置默认
            changeAttentaionStatus(isAttention);
            declare = userBean.getUserDesc();
            if (StringUtils.isBlank(declare)) {
                personal_declare_rl.setVisibility(View.GONE);
            } else {
                personal_declare_rl.setVisibility(View.VISIBLE);
                declare_tv.setText(declare);
            }
            identifyStr = userBean.getIdentificateInfo();
            if (StringUtils.isBlank(identifyStr)) {
                personal_identify_rl.setVisibility(View.GONE);
            } else {
                personal_identify_rl.setVisibility(View.VISIBLE);
                identify_tv.setText(identifyStr);
            }
        }
    }

    //设置关注
    void setAttention(int isAttention) {
        changeAttentaionStatus(isAttention);
    }

    //关注按钮的状态改变
    @UiThread
    void changeAttentaionStatus(int isAttention) {
        if (isAttention == 1) {
            attention_tv.setText(cancel_attention);
            //粉丝数+1
            if (doAttentionOrCancel) {
                fansCount++;
                fans_num_tv.setText((fansCount) + fans);
            }
        } else {
            attention_tv.setText(add_attention);
            //粉丝数-1
            if (doAttentionOrCancel) {
                fansCount--;
                fans_num_tv.setText((fansCount) + attentions);
            }
        }
    }


    void initViewPage() {
        productFragment = ProductFragment_.builder().userId(userId).build();
        attentionFragment = AttentionFragment_.builder().userId(userId).build();
        fragments = new ArrayList<Fragment>();
        fragments.add(attentionFragment);
        fManager = getSupportFragmentManager();
        fragmentAdapter = new CustomerFragmentAdapter(fManager);
        fragmentAdapter.setFragments(fragments);
        viewPager.setOffscreenPageLimit(1);//设置ViewPager缓存页面
        viewPager.setAdapter(fragmentAdapter);


        tabLayout.addTab(tabLayout.newTab().setText(R.string.personal_tablayout_tab1));
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    //设置底部ViewPager
    void setViewPager(UserBean userBean) {
        if (userBean != null) {
            isOpenShop = userBean.getIsOpenShop();
        }
        if (isOpenShop > 0) {
            if (!fragments.contains(productFragment)) {
                fragments.clear();
                fragments.add(productFragment);
                fragments.add(attentionFragment);
                fragmentAdapter.setFragments(fragments);
                fragmentAdapter.notifyDataSetChanged();
                tabLayout.removeAllTabs();
                tabLayout.addTab(tabLayout.newTab().setText(R.string.personal_tablayout_tab));
                tabLayout.addTab(tabLayout.newTab().setText(R.string.personal_tablayout_tab1));
            }
        }
    }


    //关注、取消关注（没登陆需要先登陆）
    void attentionOrCancel() {
        if (appPref.userId().get() > 0) {
            doAttentionOrCancel = true;
            if (isAttention == 0) {
                httpOperator.changeAttentionStatus(httpUtil, userId, 1, changeAttentionStatusHandler);
            } else {
                openCancelAttentionDialog();
            }
        } else {
            LoginActivity_.intent(this).startForResult(Constant.THIRD_PERSON_REQUEST_CODE);
        }
    }


    //取消关注对话框
    void openCancelAttentionDialog() {
        new MaterialDialog.Builder(cxt)
                .title(R.string.warm_prompt)
                .titleGravity(GravityEnum.CENTER)
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        httpOperator.changeAttentionStatus(httpUtil, userId, 0, changeAttentionStatusHandler);
                    }

                    @Override
                    public void onNegative(MaterialDialog dialog) {
                    }
                })
                .content(R.string.cancel_attention_dialog_content)
                .positiveText(R.string.ok)
                .negativeText(R.string.cancel)
                .show();
    }

    @Click({R.id.me_person_attention_tv, R.id.me_top_back_iv,
            R.id.me_top_attention_tv, R.id.me_top_fans_tv
            ,R.id.me_top_share_iv,R.id.me_person_icon_civ
    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.me_person_attention_tv:
                attentionOrCancel();
                break;
            case R.id.me_top_back_iv://返回按钮
                goback();
                break;
            case R.id.me_top_attention_tv:
                AttentionListActivity_.intent(cxt).flag(Constant.ATTENTION_FALG).userId(userId).start();
                break;
            case R.id.me_top_fans_tv:
                AttentionListActivity_.intent(cxt).flag(Constant.FANS_FALG).userId(userId).start();
                break;
            case R.id.me_top_share_iv:
                wxUtil.setShareContentType(Constant.URL_SHARE_TYPE);
                wxUtil.setSharePicPath(person_ico_url);
                wxUtil.openShareDialog();
                break;
            case R.id.me_person_icon_civ:
                PersonalInformationSettingActivity_.intent(cxt).start();
                break;
            default:
                break;
        }
    }

    //分享结果对话框
    void showShareResultDialog() {
        shareDialog = new MaterialDialog.Builder(cxt)
                .title(R.string.share)
                .titleGravity(GravityEnum.CENTER)
                .content(shareResult)
                .positiveText(R.string.ok)
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onNegative(MaterialDialog dialog) {
                        super.onNegative(dialog);
                    }

                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        super.onPositive(dialog);
                        shareDialog.dismiss();
                    }
                })
                .show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(this);
        StatService.onPageStart(this, Constant.THIRD_PERSONAL);
        //分享的处理
        shareResult = appPref.shareResult().get();
        if (!StringUtils.isBlank(shareResult)) {
            showShareResultDialog();
            appPref.edit().shareResult().put("").apply();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(this);
        StatService.onPageEnd(this, Constant.THIRD_PERSONAL);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
